﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using ROrganizer.Client.Files;

namespace ROrganizer.Client
{
    public class NfoFacility
    {
        public bool HasNfo(HashEntry entry)
        {
            var file = Path.ChangeExtension(entry.File, ".nfo");
            var exists = File.Exists(file);

            return exists && FileEnumerator.GetFileSize(file) < 100 * 1024;
        }

        public NfoEntry GetNfo(HashEntry entry)
        {
            if (!this.HasNfo(entry))
                return null;

            var facility = new ImdbFacility();
            var file = Path.ChangeExtension(entry.File, ".nfo");
            var data = File.ReadAllText(file);
            var query = from part in data.Split(new[]{' ', '\r', '\n'}, StringSplitOptions.RemoveEmptyEntries)
                        where Uri.IsWellFormedUriString(part, UriKind.Absolute)
                        where facility.IsValidLink(part)
                        select part;

            if(query.Distinct().Count() != 1)
                return null;

            return new NfoEntry
            {
                File = new FileEntry
                {
                    Path = entry.File,
                    Timestamp = entry.FileTimestamp
                },
                Info = new NfoInfo
                {
                    ImdbLink = query.First(),
                    ImdbId = facility.GetId(query.First())
                }
            };
        }
    }
}
